import { defineStore } from 'pinia'
import {
  getRecentPublicNotesWithStats,
  getNoteById,
  createNote,
  updateNote,
  deleteNote,
  getPublicNotesByTag,
  getLikedNotesWithStats,
  getCollectedNotesWithStats,
  getUserNotesWithStats
} from '@/api/notes'
import { useAuthStore } from '@/store/auth'
import { useLikeStore } from '@/store/likes'
import { useCollectionStore } from '@/store/collections'

// 增强的数据转换函数
const supplementNoteFields = (note) => ({
  ...note,
  id: note.id || 'unknown-note',
  title: note.title || '无标题',
  content: note.content || '',
  coverImage: note.coverImage || note.coverImageUrl || 'https://picsum.photos/id/1/800/400',
  // ✅ 强制转数字
  likes: Number(note.likes ?? 0),
  collects: Number(note.collects ?? 0),
  comments: Number(note.comments ?? 0),
  isLiked: Boolean(note.isLiked ?? false),
  isCollected: Boolean(note.isCollected ?? false),
  user: {
    id: note.user?.id || note.userId || 'unknown-user',
    name: note.user?.name || note.nickname || '匿名用户',
    avatar: note.user?.avatar || note.avatarUrl || 'https://picsum.photos/id/64/100/100'
  },
  createdAt: note.createdAt || new Date().toISOString(),
  updatedAt: note.updatedAt || new Date().toISOString()
})

export const useNoteStore = defineStore('notes', {
  state: () => ({
    recommendedNotes: [],
    nearbyNotes: [],
    userNotes: [],
    currentNote: null,
    multipleNotes: {},
    isLoading: false,
    error: null
  }),

  actions: {
  async fetchRecentPublicNotes(limit = 10) {
    this.isLoading = true
    this.error = null 
    try {
      const authStore = useAuthStore()
      const response = await getRecentPublicNotesWithStats(limit, authStore.user?.id || null) 
      if (response.code !== 200) {
        throw new Error(response.msg || '获取公开笔记失败')
      }
      const list = response.data || []
	  const mapped = list.map(supplementNoteFields)
      this.recommendedNotes = list.map(supplementNoteFields)
  
    
    } catch (e) {
      this.error = e.message || '获取推荐笔记失败'
      this.recommendedNotes = []
    } finally {
      this.isLoading = false
    }
  },

async filterNotesByTag(tagId, limit = 10) {
  this.isLoading = true
  this.error = null
  try {
    const authStore = useAuthStore()
    const response = await getPublicNotesByTag(tagId, limit, authStore.user?.id || null)

    // ✅ 直接是数组，不是 { data: [...] }
    const notes = response || []
    this.recommendedNotes = notes.map(supplementNoteFields)

    // 添加到缓存
    this.recommendedNotes.forEach(n => {
      if (n && n.id) this.multipleNotes[n.id] = n
    })
  } catch (error) {
    this.error = error.message || '按标签筛选失败'
    this.recommendedNotes = []
  } finally {
    this.isLoading = false
  }
},

    async fetchNoteById(id) {
      if (this.multipleNotes[id]) {
        this.currentNote = this.multipleNotes[id]
        return this.currentNote
      }
    
      this.isLoading = true
      this.error = null
      try {

        const rawNote = await getNoteById(id)
        if (!rawNote) throw new Error('API返回数据格式异常')

        const note = supplementNoteFields(rawNote)

        const authStore = useAuthStore()
        if (authStore.user?.id) {
          const [isLiked, isCollected] = await Promise.all([
            useLikeStore().checkIsLiked(authStore.user.id, id),
            useCollectionStore().checkIsCollected(authStore.user.id, id)
          ])
          note.isLiked = isLiked
          note.isCollected = isCollected
        }
    
        this.currentNote = note
        this.multipleNotes[id] = note
        return note
      } catch (error) {
        this.error = error.message || '获取笔记详情失败'
        this.currentNote = null
        throw error
      } finally {
        this.isLoading = false
      }
    },

    async toggleNoteLike(noteId) {
      const authStore = useAuthStore()
      const userId = authStore.user?.id
      if (!userId) return
      
      const note = this.multipleNotes[noteId]
      if (!note) return
      
      const isLiked = !note.isLiked

      const likeStore = useLikeStore()
      const success = isLiked
        ? await likeStore.likeNote(userId, noteId)
        : await likeStore.unlikeNote(userId, noteId)

      if (success) {
        note.isLiked = isLiked
        note.likes += isLiked ? 1 : -1
        this.updateNoteInLists(noteId, { isLiked, likes: note.likes })
      }
    },

    async toggleNoteCollect(noteId) {
      const authStore = useAuthStore()
      const userId = authStore.user?.id
      if (!userId) return
      
      const note = this.multipleNotes[noteId]
      if (!note) return
      
      const isCollected = !note.isCollected

      const collectionStore = useCollectionStore()
      const success = isCollected
        ? await collectionStore.collectNote(userId, noteId)
        : await collectionStore.uncollectNote(userId, noteId)

      if (success) {
        note.isCollected = isCollected
        note.collects += isCollected ? 1 : -1
        this.updateNoteInLists(noteId, { isCollected, collects: note.collects })
      }
    },

    updateNoteInLists(noteId, updates) {
      const idx = this.recommendedNotes.findIndex(n => n.id === noteId)
      if (idx > -1) Object.assign(this.recommendedNotes[idx], updates)
      
      const uIdx = this.userNotes.findIndex(n => n.id === noteId)
      if (uIdx > -1) Object.assign(this.userNotes[uIdx], updates)
      
      const nIdx = this.nearbyNotes.findIndex(n => n.id === noteId)
      if (nIdx > -1) Object.assign(this.nearbyNotes[nIdx], updates)
      
      if (this.currentNote?.id === noteId) Object.assign(this.currentNote, updates)
      
      if (this.multipleNotes[noteId]) Object.assign(this.multipleNotes[noteId], updates)
    },

    getNoteFromCache(id) {
      return this.multipleNotes[id] || null
    },

    clearCache() {
      this.multipleNotes = {}
    }
  }
})